import WebSocket,{ WebSocketServer } from 'ws';
import { ipcMain } from 'electron';

export type MessageHandler = (message: string, client: WebSocket) => void;
export type ConnectionHandler = (client: WebSocket) => void;

export default class SocketServer {
    private wss: WebSocketServer | null = null;
    private clients: Set<WebSocket> = new Set();

    private messageHandlers: MessageHandler[] = [];
    private connectionHandlers: ConnectionHandler[] = [];
    private disconnectionHandlers: ConnectionHandler[] = [];

    constructor(private port: number) {}

    // 启动 WebSocket 服务
    public start(): void {
        if (this.wss) {
            console.warn('WebSocket 服务已在运行');
            return;
        }

        this.wss = new WebSocketServer({ port: this.port });
        console.log(`WebSocket 服务已启动: ws://localhost:${this.port}`);

        this.wss.on('connection', (ws) => {
            console.log('新客户端已连接');
            this.clients.add(ws);
            this.notifyConnection(ws);

            // 消息处理
            ws.on('message', (data) => {
                const message = data.toString();
                console.log('收到消息:', message);
                this.handleMessage(message, ws);
            });

            // 错误处理
            ws.on('error', (error) => {
                console.error('WebSocket 错误:', error);
            });

            // 连接关闭
            ws.on('close', () => {
                console.log('客户端已断开');
                this.clients.delete(ws);
                this.notifyDisconnection(ws);
            });
        });

        // 注册 IPC 通信
        this.registerIpcHandlers();
    }

    // 停止 WebSocket 服务
    public stop(): void {
        if (!this.wss) return;

        // 关闭所有客户端连接
        this.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.close(1000, '服务关闭');
            }
        });
        this.clients.clear();

        // 关闭服务器
        this.wss.close(() => {
            console.log('WebSocket 服务已停止');
            this.wss = null;
        });
    }

    // 广播消息给所有客户端
    public broadcast(message: string): void {
        if (!this.wss) return;

        this.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    }

    // 发送消息给特定客户端
    public sendToClient(client: WebSocket, message: string): void {
        if (client.readyState === WebSocket.OPEN) {
            client.send(message);
        }
    }

    // 添加消息处理器
    public addMessageHandler(handler: MessageHandler): void {
        this.messageHandlers.push(handler);
    }

    // 添加连接处理器
    public addConnectionHandler(handler: ConnectionHandler): void {
        this.connectionHandlers.push(handler);
    }

    // 添加断开连接处理器
    public addDisconnectionHandler(handler: ConnectionHandler): void {
        this.disconnectionHandlers.push(handler);
    }

    // 获取客户端数量
    public getClientCount(): number {
        return this.clients.size;
    }

    // 处理消息
    private handleMessage(message: string, client: WebSocket): void {
        console.log((this.messageHandlers.length))
        this.messageHandlers.forEach(handler => handler(message, client));
    }

    // 通知连接
    private notifyConnection(client: WebSocket): void {
        this.connectionHandlers.forEach(handler => handler(client));
    }

    // 通知断开连接
    private notifyDisconnection(client: WebSocket): void {
        this.disconnectionHandlers.forEach(handler => handler(client));
    }

    // 注册 IPC 处理程序
    private registerIpcHandlers(): void {
        ipcMain.handle('get-websocket-status', () => {
            return {
                running: this.wss !== null,
                port: this.port,
                clientCount: this.getClientCount()
            };
        });

        ipcMain.on('send-to-python', (_, message: string) => {
            this.broadcast(message);
        });
    }
}